const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const dayjs = require('dayjs');
const ResponseDTO = require('./res');
// 情侣关系表
const COUPLE = 'cloud_couples'; 
const USER = 'edu-cloud-users';

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 获取登录用户信息
  let userId = wxContext.OPENID || event.userId;
  // 获取情侣信息ID
  let coupleId = event.coupleId;
  // 情侣关系标识
  let isCouple = true;

  // 未传参从数据表中尝试获取
  if(coupleId == undefined || coupleId == null){
    let coupleRes = await db.collection(COUPLE).where({
      userId
    }).get();
    if(coupleRes.data.length != 0){
      coupleId = coupleRes.data[0].coupleId;
    }else{
      isCouple = false;
    }
  }
  let userQuery = await db.collection(USER).where({
    openid:userId
  }).get();

  let userData = {};
  if(userQuery.data.length != 0){
    userData = userQuery.data[0];
  }

  let coupleQuery = await db.collection(USER).where({
    openid:coupleId || ''
  }).get();

  let coupleData = {};
  if(coupleQuery.data.length != 0){
    coupleData = coupleQuery.data[0];
  }else{
    isCouple = false;
  }

  return ResponseDTO.succData({
    userData,
    coupleData,
    isCouple
  })
}